package com.yunxi.service.dubboService.impl.sto;

import com.alibaba.cloud.context.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.yunxi.baseDataToHub.pojo.app.OrderStatusVO;
import com.yunxi.baseDataToHub.service.app.AppDubboService;
import com.yunxi.core.util.BeanTools;
import com.yunxi.core.util.DateUtil;
import com.yunxi.core.util.OSSUtil;
import com.yunxi.core.web.DictConstant;
import com.yunxi.model.order.OrderCustomer;
import com.yunxi.model.sto.StoManage;
import com.yunxi.model.sto.StoStockInPlan;
import com.yunxi.model.sto.VehicleOffline;
import com.yunxi.model.sto.VehiclePdiBill;
import com.yunxi.model.sto.VehiclePdiBillDetail;
import com.yunxi.rocketMq.producer.StoPdiCheckProducer;
import com.yunxi.service.localService.CodeCreateService;
import com.yunxi.service.localService.OrderCustomerService;
import com.yunxi.service.localService.sat.SatMessService;
import com.yunxi.service.localService.sto.StoChangeStorageService;
import com.yunxi.service.localService.sto.StoManageService;
import com.yunxi.service.localService.sto.StoStockInPlanService;
import com.yunxi.service.localService.sto.VehicleOfflineService;
import com.yunxi.service.localService.sto.VehiclePdiBillDetailService;
import com.yunxi.service.localService.sto.VehiclePdiBillService;
import com.yunxi.service.localService.sto.VehicleStockMService;
import com.yunxi.sto.pojo.ExportImgVO;
import com.yunxi.sto.pojo.PrintInfoVO;
import com.yunxi.sto.pojo.StoChangeStorageVinListVO;
import com.yunxi.sto.pojo.StoStockInPlanVO;
import com.yunxi.sto.pojo.VehiclePdiBillCheckVO;
import com.yunxi.sto.pojo.VehiclePdiBillListVO;
import com.yunxi.sto.pojo.VehiclePdiBillVO;
import com.yunxi.sto.pojo.VehicleStockFrozenVO;
import com.yunxi.sto.service.VehiclePdiBillDubboService;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.DocAttributeSet;
import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.MediaPrintableArea;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import javax.print.*;
import javax.print.attribute.DocAttributeSet;
import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.MediaPrintableArea;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 车辆pdi订单 服务实现类
 * </p>
 *
 * @author caoYong
 * @since 2019-08-14
 */
public class VehiclePdiBillDubboServiceImpl implements VehiclePdiBillDubboService {

    private static final Logger logger = LoggerFactory.getLogger(VehiclePdiBillDubboServiceImpl.class);

    @Autowired
    @Qualifier(value = "vehiclePdiBillServiceImpl")
    VehiclePdiBillService vehiclePdiBillService;

    @Autowired
    @Qualifier(value = "codeCreateServiceImpl")
    CodeCreateService codeCreateService;

    @Autowired
    @Qualifier(value = "vehiclePdiBillDetailServiceImpl")
    VehiclePdiBillDetailService vehiclePdiBillDetailService;

    @Autowired
    @Qualifier(value = "vehicleOfflineServiceImpl")
    VehicleOfflineService vehicleOfflineService;

    @Autowired
    @Qualifier(value = "stoStockInPlanServiceImpl")
    StoStockInPlanService stoStockInPlanService;

    @Autowired
    @Qualifier(value = "stoChangeStorageServiceImpl")
    StoChangeStorageService stoChangeStorageService;

    @Autowired
    @Qualifier(value = "stoManageServiceImpl")
    StoManageService stoManageService;

    @Autowired
    StoPdiCheckProducer stoPdiCheckProducer;

    @Autowired
    @Qualifier(value = "satMessServiceImpl")
    SatMessService satMessService;

    @Autowired
    @Qualifier(value = "vehicleStockMServiceImpl")
    VehicleStockMService vehicleStockMService;

    @Autowired
    RestTemplate restTemplate;

    @Value("${PRINT_URL}")
    private String printUrl;

    @Autowired
    AppDubboService appDubboService;

    @Autowired
    @Qualifier(value = "orderCustomerServiceImpl")
    OrderCustomerService orderCustomerService;

//    @Value("${pdi_rabbitmq}")
//    private String pdiRabbitmq;
//
//    @Autowired
//    private RabbitTemplate rabbitTemplate;

    @Override
    public VehiclePdiBillVO getById(String id) throws Exception {
        VehiclePdiBillVO detail = vehiclePdiBillService.getDetail(id);
        if(detail == null)throw new Exception("操作失败,无法根据主键:"+id+"找到PDI检查单!");
        String productName = vehiclePdiBillService.getProductNameByVin(detail.getVin());
        detail.setProductName(productName);//产品名称
        QueryWrapper<VehiclePdiBillDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PDI_BILL_ID",id);
        List<VehiclePdiBillListVO> list = vehiclePdiBillDetailService.queryPdiDetail(id);
        if(list != null && list.size() > 0){
            for (VehiclePdiBillListVO vo : list){
                String checkPics = vo.getCheckPics();
                if(StringUtils.isNotEmpty(checkPics)){
                    String[] split = checkPics.split(",");
                    List<String> list1 = Arrays.asList(split);
                    vo.setCheckPicsList(list1);
                }
            }
            detail.setDetailList(list);
        }
        return detail;
    }


    @Override
    public String saveOrUpdate(VehiclePdiBillVO vehiclePdiBillVO) throws Exception {
        logger.debug("==========================开始插入PDI主单============");
        String vin = vehiclePdiBillVO.getVin();
        String pdiBillId = vehiclePdiBillVO.getPdiBillId();
        if(StringUtils.isEmpty(vin))throw new Exception("操作失败,VIN码不能为空!");
        //检查车辆流转状态,是否已下线
        QueryWrapper<VehicleOffline> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("VIN",vin);
        VehicleOffline vehicleOffline = vehicleOfflineService.getOne(queryWrapper);
        if(vehicleOffline == null) throw new Exception("操作失败,VIN码:"+vin+"不存在下线记录!");
        String carState = vehicleOffline.getCarState();
        //PDI检测阶段可以多次对车辆进行PDI检测
        if(StringUtils.isEmpty(carState) || (!carState.equals(DictConstant.VEHICLE_TURN_STATE_08CLXX) && !carState.equals(DictConstant.VEHICLE_TURN_STATE_09PDI))){
            throw new Exception("操作失败,VIN码:"+vin+"车辆流转状态不是车辆下线!");
        }
        //检查PDI检查单是否重复创建
        checkPdiBillIsExist(vin, pdiBillId);
        VehiclePdiBill vehiclePdiBill = new VehiclePdiBill();
        BeanUtils.copyProperties(vehiclePdiBillVO, vehiclePdiBill);
        if(vehiclePdiBill.getPdiBillId() == null){
            String pdiNo = codeCreateService.createCode("PDI", 4);
            vehiclePdiBill.setPdiBillNo(pdiNo);
        }
        logger.debug("==========================PDI主单编号:"+vehiclePdiBill.getPdiBillNo());
        //1.生成PDI主单
        vehiclePdiBillService.saveOrUpdate(vehiclePdiBill);
        logger.debug("===============================PDI主单ID:"+vehiclePdiBill.getPdiBillId()+"==========");
        pdiBillId = vehiclePdiBill.getPdiBillId();
        //2.PDI子单
        List<VehiclePdiBillListVO> detailList = vehiclePdiBillVO.getDetailList();
        if(detailList == null || detailList.size() <= 0){
            throw new Exception("操作失败,PDI检查项不能为空!");
        }
        else{
            for (VehiclePdiBillListVO vo : detailList){
                vo.setPdiBillId(pdiBillId);
                String pdiId = vo.getPdiId();
                if(StringUtils.isEmpty(pdiId)){
                    throw new Exception("操作失败,PDI检查项主键id为空!");
                }
                VehiclePdiBillDetail vehiclePdiBillDetail1 = vehiclePdiBillDetailService.getById(vo.getDetailId());
                if(vehiclePdiBillDetail1 == null){
                    vehiclePdiBillDetail1 = new VehiclePdiBillDetail();
                    vehiclePdiBillDetail1.setPdiBillId(vo.getPdiBillId());
                    vehiclePdiBillDetail1.setPdiId(vo.getPdiId());
                }
                vehiclePdiBillDetail1.setIsOk(vo.getIsOk());
                vehiclePdiBillDetail1.setMemo(vo.getMemo());
                vehiclePdiBillDetail1.setCheckPics(vo.getCheckPics());
                vehiclePdiBillDetailService.saveOrUpdate(vehiclePdiBillDetail1);
            }
        }
        logger.debug("==========================完成插入PDI主单============");
        return pdiBillId;
    }


    @Override
    public void removeById(String id) {
        vehiclePdiBillService.removeById(id);
    }

    @Override
    public PageInfo<VehiclePdiBillVO> findPageByVO(VehiclePdiBillVO vehiclePdiBillVO, Integer pageNum, Integer pageSize) throws Exception {
        PageInfo<VehiclePdiBillVO> pageInfo = vehiclePdiBillService.pageByVo(vehiclePdiBillVO, pageNum, pageSize);
        return pageInfo;
    }

    /**
     * 导出
     * @param vehiclePdiBillVO
     * @return
     * @throws Exception
     */
    @Override
    public List<VehiclePdiBillVO> export(VehiclePdiBillVO vehiclePdiBillVO) throws Exception {
        return vehiclePdiBillService.export(vehiclePdiBillVO);
    }

    @Override
    public void removeByListVo(List<VehiclePdiBillVO> vehiclePdiBillVOList) throws Exception {
        vehiclePdiBillService.removeByListVo(vehiclePdiBillVOList);
    }

    @Override
    public List listByVo(VehiclePdiBillVO vehiclePdiBillVO) throws Exception{
        return vehiclePdiBillService.queryList(vehiclePdiBillVO);
    }

    /**
     * PDI检查
     * @param vehiclePdiBillCheckVO
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void check(VehiclePdiBillCheckVO vehiclePdiBillCheckVO) throws Exception {
        String checkStatus = vehiclePdiBillCheckVO.getCheckStatus();
        if(StringUtils.isEmpty(checkStatus)) {
            throw new Exception("操作失败,检查状态为空!");
        }
        String pdiBillId = vehiclePdiBillCheckVO.getPdiBillId();
        VehiclePdiBill vehiclePdiBill = vehiclePdiBillService.getById(pdiBillId);
        if(vehiclePdiBill == null) {
            throw new Exception("操作失败,无法根据主键:"+pdiBillId+"找到对应PDI检查单!");
        }
        vehiclePdiBill.setCheckDate(new Date());
        vehiclePdiBill.setChecker(vehiclePdiBillCheckVO.getChecker());
        vehiclePdiBill.setCheckStatus(vehiclePdiBillCheckVO.getCheckStatus());

        //2.如果检查通过,则生成入库计划
        StoStockInPlanVO stoStockInPlanVO = null;
        if(checkStatus.equals("2")){
            //3.更新车辆流转状态为PDI检查完成
            QueryWrapper<VehicleOffline> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("VIN",vehiclePdiBill.getVin());
            VehicleOffline vehicleOffline = vehicleOfflineService.getOne(queryWrapper);
            if(vehicleOffline != null){
                vehicleOffline.setCarState(DictConstant.VEHICLE_TURN_STATE_09PDI);
                vehicleOfflineService.saveOrUpdate(vehicleOffline);
                /**
                 * MQ有重复接收到PDI的情况
                 * 检查该车辆 是否已有 完成和作废以外的入库计划
                 * 如果有则不生成入库计划
                 * 防止生成重复的入库计划
                 */
                QueryWrapper<StoStockInPlan> queryStoStockInPlan = new QueryWrapper<>();
                queryStoStockInPlan.eq("VIN",vehiclePdiBill.getVin());
                queryStoStockInPlan.ne("BILL_STATE","2");
                queryStoStockInPlan.ne("BILL_STATE","3");
                int count =  stoStockInPlanService.count(queryStoStockInPlan);
                if(count==0){
                    stoStockInPlanVO = addStockinPlan(vehiclePdiBill);
                }else{
                    throw new Exception("操作失败,["+vehiclePdiBill.getVin()+"]有未完成的入库计划!");
                }
            }
        }
        //1.更新PDI主单信息
        vehiclePdiBillService.saveOrUpdate(vehiclePdiBill);
        //2.推送PDI检查完成到APP
        sentMsgToApp(vehiclePdiBill.getVin(),DictConstant.APP_RPNAME_PDI,DictConstant.APP_CODE_01);
        if(checkStatus.equals("2")){
            //调用打印机打印入库标签
            if(stoStockInPlanVO != null && StringUtils.isNotEmpty(stoStockInPlanVO.getVin())){
                newStockInImg(stoStockInPlanVO);
            }
        }
    }

    /**
     * 推送PDI检查信息到MQ
     * @param vehiclePdiBillCheckVO
     * @throws Exception
     */
    @Override
    public void checkToMQ(VehiclePdiBillCheckVO vehiclePdiBillCheckVO) throws Exception {
        stoPdiCheckProducer.sendMessage(vehiclePdiBillCheckVO);
//        if ("true".equals(pdiRabbitmq)) {
//            rabbitTemplate.convertAndSend("pdiQueue", vehiclePdiBillCheckVO);
//        } else {
//            boolean b = stoPdiCheckProducer.sendMessage(vehiclePdiBillCheckVO);
//            if(!b){
//                throw new Exception("操作失败,PDI检查信息消费失败!");
//            }
//        }
    }

    /**
     * 获取PDI检查项
     * @return
     */
    @Override
    public List<VehiclePdiBillListVO> pdiList() {
        return vehiclePdiBillService.pdiList();
    }

    /**
     * 通过VIN码查询PDI检查单
     * @param vin
     * @param isComplete
     * @return
     */
    @Override
    public List<VehiclePdiBillVO> pdiBillList(String vin, String isComplete) {
        QueryWrapper<VehiclePdiBill> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("VIN",vin);
        if(StringUtils.isNotEmpty(isComplete) && isComplete.equals("1")){
            queryWrapper.ne("CHECK_STATUS","1");
        }
        else if (StringUtils.isNotEmpty(isComplete) && isComplete.equals("0")){
            queryWrapper.eq("CHECK_STATUS","1");
        }
        List<VehiclePdiBill> list = vehiclePdiBillService.list(queryWrapper);
        List<VehiclePdiBillVO> voList = new ArrayList<>();
        if(list != null && list.size() > 0){
            voList = BeanTools.copyListToList(list, VehiclePdiBillVO.class);
        }
        return voList;
    }

    @Override
    public void printStockInImg(StoStockInPlanVO stoStockInPlanVO) throws Exception {
        newStockInImg(stoStockInPlanVO);
    }

    /**
     * 推送信息到APP
     * @param vin VIN码
     * @param rpname 业务名称
     * @param code 状态码
     * @throws Exception
     */
    @Override
    public void sentMsgToApp(String vin,String rpname,String code) throws Exception {
//        if(StringUtils.isEmpty(vin) || StringUtils.isEmpty(code)) throw new Exception("操作失败,VIN码或状态码为空!");
        //根据VIN码查询零售订单
        QueryWrapper<OrderCustomer> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("ORDER_STATUS",1,2,3,4);
        queryWrapper.in("VIN",vin);
        List<OrderCustomer> list = orderCustomerService.list(queryWrapper);
        if(list != null && list.size() > 0){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            OrderStatusVO vo = new OrderStatusVO();
            vo.setZzvin(vin);
            vo.setRpname(rpname);
            vo.setZpassd(sdf.format(new Date()));
            vo.setStCode(code);
            Integer orderStatus = list.get(0).getOrderStatus();
            String orderCustomerNo = list.get(0).getOrderCustomerNo();
            if(orderStatus != null){
                vo.setOrderStatus(orderStatus.toString());
            }
            vo.setOrderNo(orderCustomerNo);
            appDubboService.sendOrderStatusPMS2APP(vo);
        }
    }

    /**
     * 推送信息到APP
     * @param vin VIN码
     * @param rpname 业务名称
     * @param code 状态码
     * @throws Exception
     */
    @Override
    public void sentMsgToApp(String vin,String orderCustomerNo, String rpname,String code) throws Exception {
        if(StringUtils.isEmpty(vin) || StringUtils.isEmpty(code)) throw new Exception("操作失败,VIN码或状态码为空!");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        OrderStatusVO vo = new OrderStatusVO();
        vo.setZzvin(vin);
        vo.setRpname(rpname);
        vo.setZpassd(sdf.format(new Date()));
        vo.setStCode(code);
        //根据VIN码查询零售订单
        QueryWrapper<OrderCustomer> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("ORDER_STATUS",1,2,3,4);
        queryWrapper.in("VIN",vin);
        List<OrderCustomer> list = orderCustomerService.list(queryWrapper);
        if(list != null && list.size() > 0){
            Integer orderStatus = list.get(0).getOrderStatus();
            orderCustomerNo = list.get(0).getOrderCustomerNo();
            if(orderStatus != null){
                vo.setOrderStatus(orderStatus.toString());
            }
        }
        vo.setOrderNo(orderCustomerNo);
        appDubboService.sendOrderStatusPMS2APP(vo);
    }

    /**
     * 导出PDI详情
     * @param pdiBillId
     * @return
     * @throws Exception
     */
    @Override
    public VehiclePdiBillVO exportPdi(String pdiBillId) throws Exception {
        VehiclePdiBillVO byId = getById(pdiBillId);
        String vin = byId.getVin();
        List<VehiclePdiBillListVO> detailList = byId.getDetailList();
        for (VehiclePdiBillListVO vo : detailList){
            List<String> checkPicsList = vo.getCheckPicsList();
            if(checkPicsList != null && checkPicsList.size() > 0){
                List<ExportImgVO> objects = new ArrayList<>();
                for (String imgUrl : checkPicsList){
                    OSSUtil ossUtil = new OSSUtil();
                    byte[] bytes = ossUtil.downloadOSS(imgUrl);
                    ExportImgVO exportImgVO = new ExportImgVO();
                    exportImgVO.setImgByte(bytes);
                    objects.add(exportImgVO);
                }
                vo.setImgtList(objects);
            }
        }
        return byId;
    }

    private void newStockInImg(StoStockInPlanVO stoStockInPlanVO) throws Exception {
        String storageCode = stoStockInPlanVO.getStorageCode();
        QueryWrapper<StoManage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("STORAGE_CODE", storageCode);
        StoManage one = stoManageService.getOne(queryWrapper);
        if (one != null) {
            storageCode = one.getStorageFullName();
        }

        if (StringUtils.isEmpty(printUrl)) {
            logger.debug("测试环境，结束打印");
        }
        ////调用打印机服务
        PrintInfoVO printInfo = new PrintInfoVO();
        printInfo.setVin(stoStockInPlanVO.getVin());
        printInfo.setStorageName(storageCode);
        printInfo.setStockInDate(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        //请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<PrintInfoVO> request = new HttpEntity<>(printInfo, headers);
        String body = restTemplate.postForEntity(printUrl, request, String.class).getBody();
        logger.debug(stoStockInPlanVO.getVin() + "打印结果" + body);
//        InputStream inputStream = QrCodeUtils.newStockInImg(vin, storageCode, stockInDate);
//        print(inputStream);
    }

    /**
     * 打印入库标签
     * @param fis
     * @throws Exception
     */
    private void print(InputStream fis) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            if (null != fis ) {
                // 构建打印请求属性集
                PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
                // 设置打印格式，如果不是图片类型，选择 AUTOSENSE ，如果是图片类型，根据类型设置
                DocFlavor flavor = DocFlavor.INPUT_STREAM.PNG;

                // 查找所有的可用打印服务
                PrintService printService[] = PrintServiceLookup.lookupPrintServices(flavor, pras);
                // 定位默认的打印服务
                PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
                logger.debug("=====================开始打印=====================");
                if (printService != null && printService.length != 0) {
                    try {
                        List<Map<String, Object>> printerInfoList = new ArrayList<Map<String, Object>>();
                        for (int i = 0; i < printService.length; i++) {
                            Map<String, Object> printerMap = new HashMap<String, Object>();
                            printerMap.put("number", i);
                            printerMap.put("printerName", printService[i].getName());
                            printerInfoList.add(printerMap);
                            logger.debug("打印机编号--" + i);
                            logger.debug("打印机信息----" + printService[i]);
                            logger.debug("打印机服务名称----" + printService[i].getName());
                            String name = printService[i].getName();
                            if(StringUtils.isNotEmpty(name) && (name.equals("Datamax-O'Neil E-4304B Mark III") ||(name.contains("Datamax") && name.contains("E-4304B")))){
                                defaultService = printService[i];
                            }
                        }
                        map.put("list", printerInfoList);
                        // 创建打印作业（使用默认打印机）
                        DocPrintJob job = null;
                        if (null != defaultService) {
                            job = defaultService.createPrintJob();
                        } else {
                            map.put("message", "未找到打印机");
                            throw new Exception("未找到打印机");
                        }
                        job = defaultService.createPrintJob();

                        // 客户机使用 DocAttributeSet指定每个文档的特征和打印作业设置，以便将其应用到个别文档中
                        DocAttributeSet das = new HashDocAttributeSet();
                        //设置打印尺寸
                        das.add(new MediaPrintableArea(5, 5, 205, 292, MediaPrintableArea.MM));
                        // 建立打印文件格式
                        Doc doc = new SimpleDoc(fis, flavor, das);
                        job.print(doc, pras);// 进行文件的打印
                        logger.debug("=====================完成打印:" + defaultService.getName() + "=====================");
                    } catch (Exception e) {
                        e.printStackTrace();
                        map.put("message", "打印失败");
                        throw new Exception("打印失败");
                    }
                } else {
                    map.put("message", "未找到打印机");
                    throw new Exception("未找到打印机");
                }
                map.put("message", "打印成功");
            } else {
                map.put("message", "图片路径为空");
                throw new Exception("图片路径为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("message", "打印失败");
            throw new Exception("打印失败");
        }
    }

    /**
     * 检查PDI检查单是否重复创建
     * @param vin
     * @param pdiBillId
     * @throws Exception
     */
    private void checkPdiBillIsExist(String vin, String pdiBillId) throws Exception {
        QueryWrapper<VehiclePdiBill> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("VIN",vin);
        queryWrapper.eq("CHECK_STATUS","1");
        if(StringUtils.isNotEmpty(pdiBillId)){
            queryWrapper.ne("PDI_BILL_ID",pdiBillId);
        }
        List<VehiclePdiBill> list1 = vehiclePdiBillService.list(queryWrapper);
        if(list1 != null && list1.size() > 0){
            throw new Exception("操作失败,VIN码:"+vin+"已存在未完成的PDI检查单!");
        }
        QueryWrapper<StoStockInPlan> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("VIN",vin);
        queryWrapper1.ne("BILL_STATE","2");
        queryWrapper1.ne("BILL_STATE","3");
        List<StoStockInPlan> list = stoStockInPlanService.list(queryWrapper1);
        if(list != null && list.size() > 0){
            throw new Exception("操作失败,VIN码:"+vin+"存在未完成的入库计划");
        }
    }

    /**
     * 新增入库计划
     * @param vehiclePdiBill
     * @throws Exception
     */
    private StoStockInPlanVO addStockinPlan(VehiclePdiBill vehiclePdiBill) throws Exception {
        StoStockInPlanVO stoStockInPlanVO = new StoStockInPlanVO();
        stoStockInPlanVO.setPdiInsepecter(vehiclePdiBill.getChecker());
        stoStockInPlanVO.setPdaScanTime(new Date());
        stoStockInPlanVO.setVin(vehiclePdiBill.getVin());
        stoStockInPlanVO.setStockInType("1");//默认下线入库
        stoStockInPlanVO.setBillCreateTime(new Date());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(new Date());
        stoStockInPlanVO.setPlanStockInDate(format);
        //根据VIN码查询生产计划号
        QueryWrapper<VehicleOffline> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("VIN",vehiclePdiBill.getVin());
        VehicleOffline vehicleOffline = vehicleOfflineService.getOne(queryWrapper);
        if(vehicleOffline != null){
            stoStockInPlanVO.setZordNo(vehicleOffline.getZordNo());
        }
        //2.自动分配库位
        VehiclePdiBillVO vehiclePdiBillVO = new VehiclePdiBillVO();
        vehiclePdiBillVO.setPartnerCode(vehiclePdiBill.getPartnerCode());
        List<StoChangeStorageVinListVO> stoChangeStorageVinListVOS = stoChangeStorageService.storageList(vehiclePdiBillVO);
        if(stoChangeStorageVinListVOS != null || stoChangeStorageVinListVOS.size() > 0){
            for(StoChangeStorageVinListVO vo : stoChangeStorageVinListVOS){
                String isPositionFrozen = vo.getIsPositionFrozen();
                String storageCode = vo.getStorageLocation();
                if(StringUtils.isEmpty(isPositionFrozen) || isPositionFrozen.equals("0")){
                    //将库位代码写入入库计划单
                    stoStockInPlanVO.setStorageCode(storageCode);
                    //更新库位状态为占用
                    //调整为,入库完成前,冻结该库位,完成入库则更新库位使用状态为占用,解冻
                    QueryWrapper<StoManage> queryWrapper2 = new QueryWrapper();
                    queryWrapper2.eq("STORAGE_CODE",storageCode);
                    StoManage stoManage = stoManageService.getOne(queryWrapper2);
                    if(stoManage != null){
                        stoManage.setIsPositionFrozen(1);
                        stoManageService.updateById(stoManage);
                        //插入冻结历史
                        VehicleStockFrozenVO vehicleStockFrozenVO = new VehicleStockFrozenVO();
                        vehicleStockFrozenVO.setFrozenReason("计划入库");
                        vehicleStockMService.newFrozenHis("1",vehicleStockFrozenVO,storageCode,1);
                    }
                    break;
                }
            }

        }

        stoStockInPlanService.saveAndUpdate(stoStockInPlanVO);
        return stoStockInPlanVO;
    }

    /**
     * 导出详情
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public String[][] exportLoad(String id) throws Exception {
        VehiclePdiBillVO vehiclePdiBillVO = getById(id);
        String [] title = {"检查顺序","项目名称","检查标准","检查方法","是否合格","描述"};
        String[][] content = new String[vehiclePdiBillVO.getDetailList().size()][title.length];
        List<VehiclePdiBillListVO> detailList = vehiclePdiBillVO.getDetailList();

        for(int i = 0;i<detailList.size();i++){
            VehiclePdiBillListVO vehiclePdiBillListVO = detailList.get(i);
            content[i][0] = vehiclePdiBillListVO.getPdiCatalogName();
            content[i][1] = vehiclePdiBillListVO.getPdiName();
            content[i][2] = vehiclePdiBillListVO.getPdiInfo();
            content[i][3] = vehiclePdiBillListVO.getCheckMethod();
            Integer isOk = vehiclePdiBillListVO.getIsOk();
            String isRight = "";
            if(isOk != null && isOk.equals(0)){
                isRight = "否";
            }
            else {
                isRight = "是";
            }
            content[i][4] = isRight;
            content[i][5] = vehiclePdiBillListVO.getMemo();
        }
        return content;
    }
}
